﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;


namespace S.Authorization.Common.Jwt
{
    public class CustomHSJWTService : ICustomJWTService
    {
        #region Option注入

        private readonly JWTTokenOptions _JWTTokenOptions = new JWTTokenOptions();

        public CustomHSJWTService(IConfiguration configuration)
        {
            _JWTTokenOptions.SecurityKey = configuration["JWTToken:SecurityKey"];
            _JWTTokenOptions.Audience = configuration["JWTToken:Audience"];
            _JWTTokenOptions.Issuer = configuration["JWTToken:Issuer"];
        }
        #endregion Option注入

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetToken<T>(T t,string role)
        {
            //准备有效载荷
            Claim[] claims = new[]
            {
               new Claim(JwtRegisteredClaimNames.Sub, JsonConvert.SerializeObject(t)),
               new Claim(ClaimTypes.Role, role) ,// 添加角色声明
               
            };
            //List<string> functionalities = GetFunctionalitiesFromDatabase(); // 从数据库中获取功能列表

            //foreach (string functionality in functionalities)
            //{
            //    claims.Add(new Claim("功能", functionality));
            //}

            Claim[] claimsArray = claims.ToArray();
            //准备加密key
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));

            //Sha256 加密方式
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken token = new JwtSecurityToken(
                  issuer: _JWTTokenOptions.Issuer,
                  audience: _JWTTokenOptions.Audience,
                  claims: claims,
                  expires: DateTime.Now.AddMinutes(5),//5分钟有效期
                  signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}